package com.example.diarymanger.controller;

import com.example.diarymanger.bean.ApiResponse;
import com.example.diarymanger.bean.UserBean;
import com.example.diarymanger.common.R;
import com.example.diarymanger.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /*
        @Description: 注册功能
     */
    @PostMapping(value = "/register", produces = "application/json")
    public ResponseEntity<ApiResponse> register(@RequestBody UserBean userBean) {
        return userService.register(userBean);
    }

    /*
     * @Description: 登录功能
     */
    @PostMapping(value = "/login", produces = "application/json")
    public ResponseEntity<?> login(@RequestBody UserBean userBean) {
        // 调用服务层处理登录逻辑
        System.out.println(userBean);
        UserBean user = userService.login(userBean.getUsername(), userBean.getPassword());
        System.out.println("user=[" + user + "]");
        // 登录成功，可以返回用户信息或 token 等
        if (user != null) {
            // 登录成功，可以返回用户信息或 token 等
            Map<String, Object> successInfo = new HashMap<>();
            successInfo.put("success", true);
            successInfo.put("message", "Login success");
            successInfo.put("user", user); // 返回用户实体或所需的部分信息
            return ResponseEntity.ok(successInfo);
        } else {
            // 登录失败
            HashMap<String, String> errorInfo = new HashMap<>();
            errorInfo.put("error", "登录失败，账号或密码错误！");
            System.out.println("Login failed");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(errorInfo);
        }
    }

    /*
     * @更新用户信息
     */
    @PostMapping(value = "/updateUserInfo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> updateUserInfo(
            @RequestParam("uid") Integer uid,
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam("phone") String phone,
            @RequestParam("gender") String gender,
            @RequestParam("age") Integer age,
            @RequestParam("birthday") String birthday,
            @RequestParam(value = "avatar", required = false) MultipartFile avatar) {

        UserBean userBean = new UserBean();
        userBean.setUid(uid);
        userBean.setName(username);
        userBean.setPassword(password);
        userBean.setPhone(phone);
        userBean.setSex(gender);
        userBean.setAge(age);
        try {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate = LocalDate.parse(birthday, formatter);
            userBean.setBirthday(Date.valueOf(localDate)); // 假设 UserBean 中的 setBirthday 接受 java.util.Date 或 java.sql.Date
        } catch (Exception e) {
            return new ResponseEntity<>(new ApiResponse(false, "Invalid date format"), HttpStatus.BAD_REQUEST);
        }

        if (avatar != null && !avatar.isEmpty()) {
            try {
                String avatarUrl = saveAvatar(avatar); // 可以保留在这里或移到服务层
                userBean.setImageLink(avatarUrl);
            } catch (IOException e) {
                return new ResponseEntity<>(new ApiResponse(false, "Failed to save avatar"), HttpStatus.INTERNAL_SERVER_ERROR);
            }
        }

        return userService.updateUserInfo(userBean);
    }

    /**
     * 保存头像
     * @param avatar
     * @return
     * @throws IOException
     */
    private String saveAvatar(MultipartFile avatar) throws IOException {
        // 实现将头像保存到服务器或云存储，并返回其URL的逻辑
        // 示例中仅返回一个虚拟路径
        String fileName = avatar.getOriginalFilename();
        // 定义自定义存储路径（绝对路径）
        String customPath = "D:\\IDEA-Project\\schoolProject\\Diary-manger\\Diary-manger\\avatorPath";

        // 确保路径末尾有分隔符
        if (!customPath.endsWith(File.separator)) {
            customPath += File.separator;
        }

        // 创建目录（如果不存在）
        File dir = new File(customPath);
        if (!dir.exists() && !dir.mkdirs()) {
            throw new IOException("Directory '" + customPath + "' could not be created.");
        }
        // 构建完整文件路径
        String filePath = customPath + fileName;

        // 保存文件到指定路径
        File file = new File(filePath);
        avatar.transferTo(file);

        // 返回相对路径或完整URL
        return "/avatars/" + fileName; // 根据实际情况调整返回的URL前缀
    }

}
